<?php
/**
 * Created by PhpStorm.
 * User: wuchao
 * Date: 2020/5/22
 * Time: 14:53
 */

namespace app\api\controller\v1\balance;

use think\facade\Db;
use app\middleware\BackAuth;
use think\facade\Validate;
use think\Request;
use think\validate\ValidateRule;
use \Exception as E;
use think\response\Json;
class Balance
{
    // 权限校验
    protected $middleware = [BackAuth::class];

    /**入库少量选择理由
     * @param Request $request
     */
    public function WareOptions(Request $request)
    {
        $admin_id = $request->param('admin_id');//运营商ID
        if (empty($admin_id)) return jsonFail('缺少参数');
        $data = Db::table('refund_options')->where('admin_id', $admin_id)->where('type', 3)->select()->toArray();
        return jsonSuccess('获取成功', $data);
    }

    /**
     * 获取二级代理商
     * @param Request $request
     * @return mixed
     */
    public function admin_list(Request $request)
    {
        $data = Db::table('admin')->where('level', 2)->where('status', 1)->field('id,account,name,level,create_time')->select()->toArray();
        return jsonSuccess('获取成功', $data);

    }

    /**
     * 获取采购记录
     * @param Request $request
     * @return mixed
     */
    public function purchase_list(Request $request)
    {
        $sort_center_id = $request->param('sort_center_id');
        if (empty($sort_center_id)) return jsonFail('sort_center_id不能为空！');
        $data = Db::table('purchase')->alias('a')
            ->join('goods b', 'a.goods_id=b.id')
            ->where('a.center_id', $sort_center_id)
            ->where('a.type', 1)
            ->where('a.status', 1)
            ->field('a.*,b.name as goods_name,b.image')
            ->select()->toArray();
        return jsonSuccess('获取成功', $data);
    }

    /**
     * 通过二级代理商获取分拣中心ID
     * @param Request $request
     * @return mixed
     */
    public function sort_center_list(Request $request)
    {
        $admin_id = $request->param('admin_id');
        if (empty($admin_id)) return jsonFail('二级代理商ID不能为空！');
        $data = Db::table('organization')->where('admin_id', $admin_id)->select()->toArray();
        return jsonSuccess('获取成功', ['list' => $data]);
    }

    /**
     * 获取一级分类
     * @param Request $request
     * @return mixed
     */
    public function category_one(Request $request)
    {
        $admin_id = $request->param('admin_id');
        $data = Db::table('category')->where('pid', 0)->where('admin_id', $admin_id)->select()->toArray();
        return jsonSuccess('获取成功', ['list' => $data]);
    }

    /**
     * 通过一级ID获取二级分类以及三级分类
     * @param Request $request
     * @return mixed
     */
    public function category_children(Request $request)
    {
        $input['id'] = $request->post('id');
        $input['admin_id'] = $request->post('admin_id');
        // 参数校验
        $validate = Validate::rule([
            'id' => ValidateRule::isRequire(null, '缺少参数'),
            'admin_id' => ValidateRule::isRequire(null, '缺少参数'),
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        try {
            $map = [
                ['admin_id', '=', $input['admin_id']],
                ['status','=', 1],
                ['path','like',"-0-{$input['id']}-%"]
            ];
            $data = Db::table('category')->field('id,pid,name')->where($map)->select()->toArray();
            return jsonSuccess('获取成功', getTree($data));
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }

    }

    /**
     * 通过三级ID获取
     * @param Request $request
     * @return mixed
     */
    public function category_product(Request $request)
    {
        $id = $request->param('id');
        $sort_center_id = $request->param('sort_center_id');
        if (empty($id)) return jsonFail('ID不能为空！');
        if (empty($sort_center_id)) return jsonFail('sort_center_id不能为空！');
        $data = Db::table('goods')->alias('a')
            ->join('organization b ', 'b.id= a.center_id')
            ->join('goods_unit c ', 'a.unit_id= c.id')
            ->where('a.cate_id', $id)
            ->where('a.center_id', $sort_center_id)
            ->where('c.type', 1)
            ->field('a.*,b.name as center_name,c.name as unit_name')->select()->toArray();
        return jsonSuccess('获取成功', ['list' => $data]);
    }

    /**
     * 获取所有分类
     * @param Request $request
     * @return mixed
     */
    public function category_all(Request $request)
    {
        $admin_id = $request->param('admin_id');
        $data = Db::table('category')->where('pid', 0)->where('admin_id', $admin_id)->select()->toArray();
        $ids = array_column($data, 'id');
        $second = Db::table('category')->where('pid', 'in', $ids)->select()->toArray();
        $second_ids = array_column($second, 'id');
        $three = Db::table('category')->where('pid', 'in', $second_ids)->select()->toArray();
        foreach ($second as $key => &$value) {
            foreach ($three as $v) {
                if ($value['id'] == $v['pid']) {
                    $value['children'][] = $v;
                }
            }
        }
        foreach ($data as $key => &$value) {
            foreach ($second as $v) {
                if ($value['id'] == $v['pid']) {
                    $value['children'][] = $v;
                }
            }
        }
//        foreach ($data as $key => &$value) {
//            $value['children'] = Db::table('category')->where('pid', $value['id'])->select()->toArray();
//            foreach ($value['children'] as $k => &$val) {
//                $val['children'] = Db::table('category')->where('pid', $val['id'])->select()->toArray();
//            }
//        }
        return jsonSuccess('获取成功', ['list' => $data]);
    }

    /**
     * 模糊查询主订单
     * @param Request $request
     * @return mixed
     */
    public function findOrder(Request $request)
    {
        $parm = $request->param('parm');
        if (empty($parm)) return app('json')->fail('搜索字符串不能为空！');
        $data = Db::table('order')->alias('a')
            ->join('goods b', 'a.goods_id=b.id')
            ->join('goods_unit c', 'b.unit_id=c.id')
            ->where('a.status', 0)
            ->where('a.is_pay', 1)
            ->whereLike('a.order_no', '%' . $parm . '%')
            ->field('a.*,b.stock,b.ice_stock,c.name as unit_name')
            ->select()->toArray();
        return jsonSuccess('获取成功', $data);
    }

    /**
     * 根据主订单
     * @param Request $request
     * @return mixed
     */
    public function findsubOrder(Request $request)
    {
        $order_id = $request->param('order_id');
        $sort_center_id = $request->param('sort_center_id');
        if (empty($order_id)) return jsonFail('订单ID不能为空！');
        if (empty($sort_center_id)) return jsonFail('sort_center_id不能为空！');
        $field = 'a.id,a.role_type,a.mastr_order_no,a.order_no,a.goods_id,a.total_price,a.num,a.remark,a.center_name,a.goods_data,
            a.status,a.back_reason,a.unback_reason,a.back_time,a.is_pay,a.pay_time,a.code,a.create_time,
            c.name as arrive_name,c.phone as arrive_phone,c.province,c.city,c.area,c.address
            ,d.name as company_name';
        $data = Db::table('order')->alias('a')
            ->join('goods b', 'a.goods_id=b.id')
            ->join('company_address c', 'a.address_id=c.id')
            ->join('company d', 'a.group_id=d.id')
            ->where('a.center_id', $sort_center_id)
            ->where('a.id', $order_id)
            ->field($field)
            ->select()->toArray();
        $NewData = self::GetRepeatValGroup($data, 'mastr_order_no');//TODO 组合数据
        return jsonSuccess('获取成功', $NewData);
    }

    /**
     * 根据商品获取订单
     * @param Request $request
     * @return mixed
     */
    public function get_order(Request $request)
    {
        $product_id = $request->param('product_id');
        $sort_center_id = $request->param('sort_center_id');
        $data = Db::table('order')->alias('a')
            ->join('organization b ', 'b.id= a.center_id')
            ->join('goods d', 'a.goods_id=d.id')
            ->join('goods_unit c ', 'd.unit_id= c.id')
            ->where('a.is_pay', 1)
            ->where('a.status', 0)
            ->where('a.center_id', $sort_center_id)
            ->where('a.goods_id', $product_id)
            ->where('c.type', 1)
            ->field('a.*,d.stock,d.ice_stock,b.name as center_name,c.name as unit_name')
            ->select()->toArray();
        return jsonSuccess('获取成功', $data);
    }

    /**
     * 未秤重订单
     * @param Request $request
     * @return mixed
     */
    public function order_out(Request $request)
    {
        $type = $request->param('type', 1);//分拣中心
        $center_id = $request->param('center_id');
        if (empty($center_id)) return jsonFail('缺少参数');
        if ($type == 2) {
            $data = Db::table('order')->alias('a')
                ->join('organization b ', 'b.id= a.center_id')
                ->join('goods c ', 'c.id= a.goods_id')
                ->join('goods_unit d ', 'c.unit_id= d.id')
                ->join('company e', 'a.group_id = e.id')
                ->join('user f', 'a.user_id = f.id')
                ->where('a.is_pay', 1)
                ->where('a.status', 0)
                ->where('a.center_id', $center_id)
                ->field('a.*,c.stock,c.ice_stock,b.name as center_name,d.name as unit_name,d.type,e.name as company_name,f.phone')->select()->toArray();
        } else {
            $data = Db::table('order')->alias('a')
                ->join('organization b ', 'b.id= a.center_id')
                ->join('goods c ', 'c.id= a.goods_id')
                ->join('goods_unit d ', 'c.unit_id= d.id')
                ->join('company e', 'a.group_id = e.id')
                ->join('user f', 'a.user_id = f.id')
                ->where('a.is_pay', 1)
                ->where('a.status', 0)
                ->where('a.center_id', $center_id)
                ->where('d.type', 1)
                ->field('a.*,c.stock,c.ice_stock,b.name as center_name,d.name as unit_name,d.type,e.name as company_name,f.phone')->select()->toArray();
        }
        return jsonSuccess('获取成功', $data);
    }

    /**
     * 商品称重入库
     * @param Request $request
     * @return mixed
     */
    public function Goods_in_stock(Request $request)
    {
        try {
            $equipment = $request->param('equipment');//设备号
            $product_id = $request->param('product_id');//商品ID
            $Warehousing_id = $request->param('Warehousing_id');//入库人ID
            $weight = $request->param('weight');//重量
            $admin_id = $request->param('admin_id');//运营商ID
            $purchase_id = $request->param('purchase_id');//采购记录ID
            $reason = $request->param('reason', '');//原因
            if (empty($purchase_id) || empty($admin_id) || empty($equipment) || empty($product_id) || empty($Warehousing_id) || empty($weight)) return jsonFail('缺少参数');
            $role = Db::table('admin')->alias('a')
                ->where('a.id', $Warehousing_id)
                ->join('role b ', 'a.role_id= b.id')
                ->field('a.name,a.phone,b.name as role_type')
                ->find();
            if (empty($role)) return jsonFail('操作人信息有误');
            $unit_name = Db::table('goods')->alias('a')->join('goods_unit b ', 'a.unit_id= b.id')
                ->where('a.id', $product_id)->field('b.name,a.ot_price_percent,a.price_percent')->find();
            switch ($unit_name['name']) {//单位换算
                case "斤"://斤
                    $weights = $weight * 2;
                    break;
                case "公斤":
                    $weights = $weight;
                    break;
            }
            $purchase_data = Db::table('purchase')
                ->field('price')
                ->where('id', $purchase_id)->find();
            if (empty($purchase_data)) return jsonFail('信息有误');
            Db::startTrans();
            $res = Db::table('goods')->where('id', $product_id)->update([
                'stock' => Db::raw("`stock` + {$weights}"),
                'ot_price' => round($purchase_data['price'] * $unit_name['ot_price_percent'] / 100, 2),
                'price' => round($purchase_data['price'] * $unit_name['price_percent'] / 100, 2),
                'pur_price' => $purchase_data['price']
            ]);
            if ($res) {
                //记录日志
                $red = Db::table('goods_log')->insertGetId([
                    'type' => 1,
                    'uid' => $Warehousing_id,
                    'goods_id' => $product_id,
                    'equipment' => $equipment,
                    'order_id' => $purchase_id,
                    'weight' => $weights,
                    'admin_id' => $admin_id,
                    'name' => $role['name'],
                    'phone' => $role['phone'],
                    'role_type' => $role['role_type'],
                    'create_time' => time(),
                ]);
                //更新采购记录
                $red = Db::table('purchase')->where('id', $purchase_id)->update([
                    'w_weight' => $weights,
                    'status' => 2,
                    'reason' => $reason,
                ]);
                if ($red != 0) {
                    DB::commit();
                    return jsonSuccess('入库成功');
                } else {
                    DB::rollback();
                    return jsonFail('入库失败');
                }
            } else {
                DB::rollback();
                return jsonFail('入库失败');
            }
        } catch (\Exception $e) {
            DB::rollback();
            return jsonFail($e->getMessage());
        }
    }

    /**
     * 商品称重出库
     * @param Request $request
     * @return mixed
     */
    public function Goods_out_stock(Request $request)
    {
        try {
            $input['equipment'] = $request->post('equipment', '');//设备号
            $input['product_id'] = $request->post('product_id');//商品ID
            $input['order_id'] = $request->post('order_id');
            $input['weight'] = $request->post('weight');//份数
            $input['retrieval_id'] = $request->post('retrieval_id');//出库人ID
            $input['admin_id'] = $request->post('admin_id');//运营商ID
            $validate = Validate::rule([
                'admin_id' => ValidateRule::isRequire(null, '缺少参数'),
                'product_id' => ValidateRule::isRequire(null, '缺少参数'),
                'order_id' => ValidateRule::isRequire(null, '缺少参数'),
                'weight' => ValidateRule::isRequire(null, '缺少参数'),
                'retrieval_id' => ValidateRule::isRequire(null, '缺少参数'),
            ]);
            if (!$validate->check($input)) {
                return jsonFail($validate->getError());
            }
            $role = Db::table('admin')->alias('a')
                ->where('a.id', $input['retrieval_id'])
                ->join('role b ', 'a.role_id= b.id')
                ->field('a.name,a.phone,b.name as role_type')
                ->find();
            if (empty($role)) return jsonFail('操作人信息有误');
            $unit_name = Db::table('goods')->alias('a')->join('goods_unit b ', 'a.unit_id= b.id')
                ->where('a.id', $input['product_id'])->field('a.ice_stock,a.center_id,b.name')->find();
            switch ($unit_name['name']) {//单位换算
                case "斤"://斤
                    $weights = $input['weight'] * 2;
                    break;
                case "公斤":
                    $weights = $input['weight'];
                    break;
                default:
                    $weights = $input['weight'];
                    break;
            }
            $order = Db::table('order')->where('id', $input['order_id'])->field('group_id,user_id,goods_data,num')->find();
            $back_money = 0;
            if ($weights < $order['num']) {//当前重量小于所需量
                $goods_info = json_decode($order['goods_data'], true);
                $back_money = ($order['num'] - $weights) * $goods_info['price'];
                Db::table('user')->where('id', $order['user_id'])->inc('integral', $back_money)->update();
                $Difference = $order['num'] - $weights;
                $res = Db::table('goods')->where('id', $input['product_id'])->dec('ice_stock', $order['num'])->inc('stock', $Difference)->update();
            } else if ($weights >= $order['num']) {//当前重量大于所需量
                $Difference = $weights - $order['num'];
                $res = Db::table('goods')->where('id', $input['product_id'])->dec('ice_stock', $order['num'])->dec('stock', $Difference)->update();
            }
            $driver_id = Db::table('company')->where('id', $order['group_id'])->value('driver_id');
            $res = Db::table('order')->where('id', $input['order_id'])->where('status', 0)->where('goods_id', $input['product_id'])->update(['status' => 1, 'retrieval_id' => $input['retrieval_id'], 'driver_id' => $driver_id]);//子订单发货
            if ($res) {
                $red = Db::table('goods_log')->insertGetId([
                    'type' => 2,
                    'admin_id' => $input['admin_id'],
                    'uid' => $input['retrieval_id'],
                    'goods_id' => $input['product_id'],
                    'order_id' => $input['order_id'],
                    'equipment' => $input['equipment'],
                    'weight' => $weights,
                    'name' => $role['name'],
                    'phone' => $role['phone'],
                    'role_type' => $role['role_type'],
                    'create_time' => time(),
                ]);
                $red = Db::table('order_status')->insertGetId([
                    'oid' => $input['order_id'],
                    'change_message' => '已出库, 出库人ID：' . $input['retrieval_id'] . ' 出库设备：' . $input['equipment'] . '，出库重量：' . $weights,
                    'name' => $role['name'],
                    'phone' => $role['phone'],
                    'role_type' => $role['role_type'],
                    'create_time' => time(),
                ]);
                if ($red != 0) {
                    DB::commit();
                    return jsonSuccess('出库成功');
                } else {
                    DB::rollback();
                    return jsonFail('出库失败');
                }
            } else {
                DB::rollback();
                return jsonFail('出库失败');
            }
        } catch (\Exception $e) {
            DB::rollback();
            return jsonFail('服务内部错误', [$e->getMessage(), $e->getLine()]);
        }
    }

    /**
     * 商品减少库存
     * @param Request $request
     * @return mixed
     */
    public function Goods_reduce(Request $request)
    {
        try {
            $equipment = $request->param('equipment');//设备号
            $product_id = $request->param('product_id');//商品ID
            $weight = $request->param('weight');//重量
            $retrieval_id = $request->param('retrieval_id');//出库人ID
            $admin_id = $request->param('admin_id');//运营商ID
            $reason = $request->param('reason', '');//原因
            if (empty($admin_id) || empty($equipment) || empty($product_id) || empty($retrieval_id) || empty($weight)) return jsonFail('缺少参数');
            $role = Db::table('admin')->alias('a')
                ->where('a.id', $retrieval_id)
                ->join('role b ', 'a.role_id= b.id')
                ->field('a.name,a.phone,b.name as role_type')
                ->find();
            if (empty($role)) return jsonFail('操作人信息有误');
            $unit_name = Db::table('goods')->alias('a')->join('goods_unit b ', 'a.unit_id= b.id')
                ->where('a.id', $product_id)->field('a.ice_stock,a.center_id,b.name')->find();
            switch ($unit_name['name']) {//单位换算
                case "斤"://斤
                    $weights = $weight * 2;
                    break;
                case "公斤":
                    $weights = $weight;
                    break;
            }
            Db::startTrans();
            $res = Db::table('goods')->where('id', $product_id)->update(['stock' => $weights]);
            if ($res) {
                $red = Db::table('goods_log')->insertGetId([
                    'type' => 3,
                    'admin_id' => $admin_id,
                    'uid' => $retrieval_id,
                    'goods_id' => $product_id,
                    'equipment' => $equipment,
                    'weight' => $weights,
                    'name' => $role['name'],
                    'phone' => $role['phone'],
                    'role_type' => $role['role_type'],
                    'create_time' => time(),
                    'reason' => $reason,
                ]);
                if ($red != 0) {
                    DB::commit();
                    return jsonSuccess('报损成功');
                } else {
                    DB::rollback();
                    return jsonFail('报损失败');
                }
            } else {
                DB::rollback();
                return jsonFail('报损失败');
            }
        } catch (\Exception $e) {
            DB::rollback();
            return jsonFail($e->getMessage());
        }
    }

    /**
     * 秤更新
     * @param Request $request
     * @return mixed
     */
    public function UpdateBalance(Request $request)
    {
        $version = $request->param('version');//版本号
        if (empty($version)) return jsonFail('缺少参数');
        // 获取自动收货时间
        $config_version = Db::table('eb_config')->where('name', 'update_balance')->find();
        if ($config_version['value'] != $version) {
            return jsonSuccess('获取成功', ['is_update' => 1, 'url' => $config_version['describe'] . $config_version['value'] . '.apk']);
        } else {
            return jsonSuccess('获取成功', ['is_update' => 0, 'url' => '']);
        }
    }

    /*
    * 判断子订单是否全部发货
    * @param int $id
    * @return boolean
    * */
    public function select_type($order)
    {
        $temp = 0;
        foreach ($order as $key => $value) {
            if ($temp == 0) {
                $temp = $value['status'];
            } else {
                if ($temp != $value['status']) {
                    return false;
                }
            }
        }
        return true;
    }

    /**组合数据，相同的分类为二维，商品为三维
     * @param array $input
     * @return Json
     */
    public static function GetRepeatValGroup($arr, $keys)
    {
        if (!is_array($arr) || !$keys) {
            return false;
        }
        $temp = array();
        $total_price = 0;
        foreach ($arr as $key => $val) {
//            $total_price+= $val['total_price'];
            $temp[$val[$keys]]['id'] = $val['id'];
            $temp[$val[$keys]]['mastr_order_no'] = $val['mastr_order_no'];
            $temp[$val[$keys]]['role_type'] = $val['role_type'];
//            $temp[$val[$keys]]['center_name'] = $val['center_name'];
            $temp[$val[$keys]]['company_name'] = $val['company_name'];
            $temp[$val[$keys]]['sub_order'][] = $val;
            foreach ($temp[$val[$keys]]['sub_order'] as $key => &$value) {
                unset($value['id']);
                unset($value['mastr_order_no']);
                unset($value['role_type']);
                unset($value['company_name']);
//                unset($value['center_name']);
            }
        }
//        $temp['']
        return $temp;
    }

    /**获取需要出库的商品以及数量
     * @param Request $request
     * @return Json
     */
    public function getOut(Request $request)
    {
        // 获取参数
        $input['center_id'] = $request->post('center_id');
        // 参数校验
        $validate = Validate::rule([
            'center_id' => ValidateRule::isRequire(null, '缺少参数')
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        try {
            $map = [
                ['center_id', '=', $input['center_id']],
                ['status', '=', 0]
            ];
            $info = Db::table('order')->field('goods_data,num')->where($map)->select()->toArray();
            if (!$info) return jsonSuccess('未找到数据',[]);
            $data = [];
            foreach ($info as $item) {
                $goods = json_decode($item['goods_data'], true);
                if ($goods['unit_type'] == 2) continue;
                $data[] = [
                    'goods_name' => $goods['name'],
                    'goods_unit' => $goods['unit_name'],
                    'goods_num' => $item['num'],
                    'goods_id' => $goods['id']
                ];
            }
            return jsonSuccess('获取成功', $data);
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取需要等待出库的订单信息
     * @param Request $request
     * @return Json
     */
    public function getWaitOrder(Request $request)
    {
        // 获取参数
        $input['center_id'] = $request->post('center_id');
        // 参数校验
        $validate = Validate::rule([
            'center_id' => ValidateRule::isRequire(null, '缺少参数')
        ]);

        if (!$validate->check($input)) {
            return jsonFail($validate->getError());
        }
        // 逻辑处理
        try {
            $map = [
                ['o.center_id', '=', $input['center_id']],
                ['o.status', '=', 0],
                ['gu.type', '=', 1]
            ];
            $info = Db::table('order')->alias('o')
                ->leftJoin(['goods' => 'g'], 'g.id = o.goods_id')
                ->leftJoin(['company' =>'c'], 'c.id = o.group_id')
                ->leftJoin(['user' => 'u'], 'u.id = o.user_id')
                ->leftJoin(['goods_unit' => 'gu'], 'gu.id = g.unit_id')
                ->field('o.id,o.num,goods_data,mastr_order_no,gu.name as unit_name,g.stock,g.ice_stock,c.name as company_name,u.phone,order_no')
                ->where($map)
                ->select()->toArray();
            if (!$info) return jsonSuccess('未找到数据',[]);
            return jsonSuccess('获取成功', $info);
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }
}